#!/bin/bash

# WebSocket连接测试脚本

echo "=========================================="
echo "WebSocket连接测试脚本"
echo "=========================================="

# 检查后端服务是否运行
echo "检查后端服务状态..."
if curl -s http://localhost:8086/actuator/health > /dev/null 2>&1; then
    echo "✅ 后端服务正在运行 (端口 8086)"
else
    echo "❌ 后端服务未运行，请先启动后端服务"
    echo "启动命令: cd kaizelioa-be && mvn spring-boot:run"
    exit 1
fi

# 测试WebSocket连接
echo ""
echo "测试WebSocket连接..."
echo "连接地址: ws://localhost:8086/ws/warning"

# 使用Node.js测试WebSocket连接（如果安装了Node.js）
if command -v node &> /dev/null; then
    echo "使用Node.js测试WebSocket连接..."
    node -e "
const WebSocket = require('ws');
const ws = new WebSocket('ws://localhost:8086/ws/warning');

ws.on('open', function open() {
    console.log('✅ WebSocket连接成功！');
    ws.send(JSON.stringify({type: 'ping', message: '测试消息'}));
});

ws.on('message', function message(data) {
    console.log('📨 收到消息:', data.toString());
});

ws.on('error', function error(err) {
    console.log('❌ WebSocket连接错误:', err.message);
});

ws.on('close', function close() {
    console.log('🔌 WebSocket连接已关闭');
});

setTimeout(() => {
    ws.close();
    process.exit(0);
}, 3000);
"
else
    echo "⚠️  未安装Node.js，无法自动测试WebSocket连接"
    echo "请手动打开 websocket-test.html 文件进行测试"
fi

echo ""
echo "=========================================="
echo "测试完成"
echo "=========================================="
